package cn.csust.net2.manager.client.module;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.csust.net2.manager.client.app.App;
import cn.csust.net2.manager.client.ux.BeanGridPanel;
import cn.csust.net2.manager.client.ux.ExpandTree;
import cn.csust.net2.manager.shared.po.Academy;
import cn.csust.net2.manager.shared.po.Research;
import cn.csust.net2.manager.shared.po.ResearchAnswer;
import cn.csust.net2.manager.shared.po.ResearchTitle;
import cn.csust.net2.manager.shared.po.Student;
import cn.csust.net2.manager.shared.service.ByGradeService;
import cn.csust.net2.manager.shared.service.ByGradeServiceAsync;
import cn.csust.net2.manager.shared.service.ResearchManagerService;
import cn.csust.net2.manager.shared.service.ResearchManagerServiceAsync;
import cn.csust.net2.manager.shared.util.ClassForNameAble;
import cn.csust.net2.manager.shared.util.POConstant;
import cn.csust.net2.manager.shared.vo.Config;
import cn.csust.net2.manager.shared.vo.TreeNode;

import com.extjs.gxt.charts.client.Chart;
import com.extjs.gxt.charts.client.model.ChartModel;
import com.extjs.gxt.charts.client.model.ToolTip;
import com.extjs.gxt.charts.client.model.ToolTip.MouseStyle;
import com.extjs.gxt.charts.client.model.axis.XAxis;
import com.extjs.gxt.charts.client.model.axis.YAxis;
import com.extjs.gxt.charts.client.model.charts.HorizontalBarChart;
import com.extjs.gxt.charts.client.model.charts.HorizontalBarChart.Bar;
import com.extjs.gxt.ui.client.Style;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.TabPanel.TabPosition;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.Time;
import com.extjs.gxt.ui.client.widget.form.TimeField;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanelSelectionModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.rpc.AsyncCallback;

@ClassForNameAble
public class ResearchManager extends BaseModule {
	//服务
	private ByGradeServiceAsync byGradeservice;
	private ResearchManagerServiceAsync managerService;
	
	private ExpandTree boundTree;
	private Window treeWindow ;
	//用来保存当前调研所绑定的学生
	private List<Long> studentNumberList;
	//投票结果
	private Map<Long, Long> resultMap = new HashMap<Long, Long>();
	
	private TreePanel<ModelData> tree; 
	private HtmlEditor editor;
	private TreeStore<ModelData> store ; 
	private TextField<String> topicText ;

	
	private DateField startDate; 
	private DateField endDate ;
	private TimeField startTime ;
	private TimeField endTime  ;
//	private ByGrade selectStudentGrid;
	//显示 research 中
	private LayoutContainer chartsContainer;

	public ResearchManager() {
		this.setText("管理调研");
		this.setId("管理调研");
		this.setClosable(true);
//		EntranceRegistrationPanel panel = new EntranceRegistrationPanel();
//		this.add(panel);
		init();
		
		
		TabPanel folder = new TabPanel(); 
		folder.setSize("%100", "%100");
		
		TabItem createItem = new TabItem("创建调研");
		createItem.setSize("%100", "%100");
		createItem.setScrollMode(Scroll.AUTO);
		createItem.setLayout(new RowLayout(Style.Orientation.HORIZONTAL));
		createItem.add(createFormPanle(),new RowData(0.59, 400, new Margins(5, 5, 5, 5)));
	    createItem.add(createPreviewPanel() ,new RowData(0.39, 440, new Margins(5, 5, 5, 5)));
	
		TabItem managerItem = new TabItem("调研统计");
		managerItem.setSize("%100", "%100");
		managerItem.setLayout(new RowLayout(Style.Orientation.HORIZONTAL));
		managerItem.setLayoutOnChange(true);
		managerItem.setScrollMode(Scroll.AUTO);
		
		managerItem.add(getBeanGridPanel(), new RowData(0.55, 1, new Margins(
				5, 5, 5, 5)));
		managerItem.add(chartsContainer, new RowData(0.45, 440, new Margins(5, 5, 5,
				5)));
		
		folder.add(createItem);
		folder.add(managerItem);
		folder.setTabPosition(TabPosition.BOTTOM); 
		this.setLayout(new FitLayout());
		this.add(folder);
		this.addStyleName("pad-text");
		
		

	}

	public void init(){
		initTreeWindow();
		managerService= GWT.create(ResearchManagerService.class);
		chartsContainer = new LayoutContainer(new RowLayout());
		chartsContainer.setLayoutOnChange(true);
		chartsContainer.setScrollMode(Scroll.AUTO);
		changeChartContainer(null,null);
	}
	
	public void initTreeWindow(){
		treeWindow = new Window();		
		treeWindow.setLayoutOnChange(true);
		treeWindow.setLayout(new FitLayout());
		treeWindow.setSize(250, 500);
	}

	
	/*
	 * 加载显示学生的tree
	 */
	public void loadStudentTree(){
		if(byGradeservice==null){
			byGradeservice = GWT.create(ByGradeService.class);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(ExpandTree.TEACHER_ADD, false);
		map.put(ExpandTree.CHECKABLE, true);
		
		boundTree = new ExpandTree(Student.class,true,map) {
			@Override
			protected void load(Object loadConfig, Map<String, Object> configs,
					AsyncCallback<List<TreeNode>> callback) {

				byGradeservice.getChildren((TreeNode) loadConfig, configs, callback);
			}

			@Override
			protected void load(String[] items) {
				Config c = new Config();
				c.put(ExpandTree.GRADE_ITEMS, items);
				boundTree.load(Student.class,c);
			}
		};
		initTreeWindow();
		boundTree.getTree().setAutoExpand(true);
		boundTree.getTree().setCheckable(false);
		treeWindow.add(boundTree);

	}
	
	/*
	 * 设置调研学生用于显示学生的window
	 */
	public void settingResearchStudentTreePanel(final Research research){
		if(studentNumberList == null){
			MessageBox.alert("提示", "正在加载相关数据请稍等片刻再试", null);
			return;
		}
		treeWindow.setHeading(research.getTopic());		
		treeWindow.addButton(new Button("编辑", new SelectionListener<ButtonEvent>() {		
//			@Override
			public void componentSelected(ButtonEvent ce) {			
						boundTree.getTree().setCheckable(true);
						List<BeanModel> items = boundTree.getTree().getStore().getAllItems();
//						System.out.println("getAllItems:"+items.size());
						for(BeanModel model:items){
							//如果是学生并且数据库中已经有的数据就选中
							if(model.getBean() instanceof Student){
								if(studentNumberList.contains(((Student)model.getBean()).getUserID())){
									boundTree.getTree().setChecked(model, true);
								}								
							}
						}
						for(BeanModel model : items){
							if(model.getBean() instanceof Academy){
								boundTree.getTree().setExpanded(model, false);
								boundTree.getTree().setExpanded(model, true);
							}
						}				
		
			}
		}));
		treeWindow.addButton(new Button("保存", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				List<BeanModel> models = boundTree.getTree().getCheckedSelection();
//				System.out.println(models.size()+" this is size");
				List<Long> numberList = new ArrayList<Long>();
				for(BeanModel model:models){					
					if(model.getBean() instanceof Student){
						numberList.add(((Student)model.getBean()).getUserID());
					}
				}
				PagingLoadConfig config = new BasePagingLoadConfig();
				config.set(ResearchManagerService.RESEARCHID,research.getResearchId());
				config.set(ResearchManagerService.STUDENT_NUMBERL_LIST,numberList);
				studentNumberList = numberList;
				managerService.saveResearchStudentsByPaging(config, new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						MessageBox.alert("提示", "保存失败", null);
						
					}

					@Override
					public void onSuccess(Void result) {
						MessageBox.alert("提示", "保存成功", null);
						
					}
					
				});

			}
		}));	
	}
	
	public TreePanel<ModelData> getCheckPanel(Research research){
		final TreeStore<ModelData> store = new TreeStore<ModelData>();
		if(research==null){
			return new TreePanel<ModelData>(store);
		}
		PagingLoadConfig config = new BasePagingLoadConfig();
		config.set(ResearchManagerService.RESEARCHID, research.getResearchId());
		managerService.findResearchTitlesByPaging(config, new AsyncCallback<PagingLoadResult<ResearchTitle>>() {
			
			@Override
			public void onSuccess(PagingLoadResult<ResearchTitle> result) {
				for(ResearchTitle title : result.getData()){					
					final BaseTreeModel model = new BaseTreeModel();
					model.set("name", title.getQuestion());
					store.add(model, false);;
					PagingLoadConfig conf = new BasePagingLoadConfig();
					conf.set(ResearchManagerService.RESERACH_TITLEID, title.getTitleId());
					managerService.findResearchAnswersByPaging(conf, new AsyncCallback<PagingLoadResult<ResearchAnswer>>() {
						
						@Override
						public void onSuccess(PagingLoadResult<ResearchAnswer> result) {
							for(ResearchAnswer answer: result.getData()){
								BaseTreeModel m = new BaseTreeModel(model);
								m.set("name", answer.getAnswer());
								store.add(model,m, false);
							}							
						}
						
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("", "get reserchAnswers failed", null);
							
						}
					});
				}
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("", "get reserchTitles failed", null);
				
			}
		});
		
		TreePanel<ModelData> tree = new TreePanel<ModelData>(store);
		
		
		return tree;
	}
	
	
	/*
	 * 用来显示调研的grid
	 */
	public BeanGridPanel<Research> getBeanGridPanel() {
			
		final BeanGridPanel<Research> grid = new BeanGridPanel<Research>(new Research(),
				managerService);
		grid.setAutoLoad(true);
		grid.createDefault();
		grid.getGrid()
				.getSelectionModel()
				.addSelectionChangedListener(
						new SelectionChangedListener<BeanModel>() {
							@Override
							public void selectionChanged(
									SelectionChangedEvent<BeanModel> se) {
								studentNumberList = null;
								Research research = (Research) se.getSelectedItem().getBean();
								loadStudentNumberList(research);
								changeChartContainer(research,null);
							}
						});
		
		Button edit = new Button("设置调研学生",new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				if(grid.getGrid().getSelectionModel().getSelectedItem()==null){
					MessageBox.alert("提示","请选择一个调研！" , null);
				}else{
					Research research = grid.getGrid().getSelectionModel().getSelectedItem().getBean();
					loadStudentTree();
					settingResearchStudentTreePanel(research);
					treeWindow.show();					
				}
			}
		});
		
		Button statistics = new Button("统计调研", new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				if(grid.getGrid().getSelectionModel().getSelectedItem()==null){
					MessageBox.alert("提示","请选择一个调研！" , null);
				}else{
					Research research = grid.getGrid().getSelectionModel().getSelectedItem().getBean();
					loadStudentTree();
					statisticsResearch(research);
					treeWindow.show();
				}
				
			}
		});
		grid.getToolBar().add(edit);
		grid.getToolBar().add(statistics);
		return grid;
	}	
	
	
	private void loadStudentNumberList(Research research){
		managerService.getResearchStudentNumberList(research.getResearchId(), new AsyncCallback<List<Long>>() {
			
			@Override
			public void onSuccess(List<Long> result) {
				studentNumberList = result;
				System.out.println("已经重新加载学生信息:"+studentNumberList);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("提示","加载信息失败！" , null);			
			}
		});
	}
	
	/*
	 * 在统计的时候只能看到绑定的学生
	 */
//	boolean loadStudentFlag = true;
	private void statisticsResearch(final Research research) {
		if(studentNumberList ==null){
			MessageBox.alert("提示", "正在加载相关数据请稍等片刻再试", null);
			return;
		}

		treeWindow.addButton(new Button("进行选择", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				//获取全部节点
				boundTree.getTree().setCheckable(true);
	 			List<BeanModel> items = boundTree.getTree().getStore().getAllItems();
	 			List<BeanModel> removeItems = new ArrayList<BeanModel>();
	 			for(BeanModel model : items){
	 				if(model.getBean() instanceof Student){
	 					//如果此节点是可以调研的学生则显示，不是则不限是
	 					if(studentNumberList.contains(((Student)model.getBean()).getUserID())){
	 						boundTree.getTree().setChecked(model, true);
	 					}else {
	 						boundTree.getTree().setChecked(model, false);
	 						removeItems.add(model);
	 					}
	 				}
	 			}
	 			
	 			for(BeanModel m: removeItems){
	 				boundTree.getTree().getStore().remove(m);
	 			}
	 			
	 			for(BeanModel model : items){
					if(model.getBean() instanceof Academy){
						boundTree.getTree().setExpanded(model, false);
						boundTree.getTree().setExpanded(model, true);
					}
				}	
			}
		}));
		treeWindow.addButton(new Button("开始统计统计", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				List<Long> list = new ArrayList<Long>();
				for(BeanModel m :boundTree.getTree().getStore().getAllItems()){
					if(m.getBean() instanceof Student && boundTree.getTree().isChecked(m)){
						list.add(((Student)m.getBean()).getUserID());
					}
				}
 				changeChartContainer(research,list );
			}
		}));
		
	}
	
	
	 public void setTitleAndChartModel(final ResearchTitle title,final Chart chart) {

		 PagingLoadConfig config  = new BasePagingLoadConfig();
		 config.set(ResearchManagerService.RESEARCH_TITLEID, title.getTitleId());
		 final List<ResearchAnswer> answerList = new ArrayList<ResearchAnswer>();
		 managerService.findResearchAnswersByPaging(config, new AsyncCallback<PagingLoadResult<ResearchAnswer>>() {
			
			@Override
			public void onSuccess(PagingLoadResult<ResearchAnswer> result) {
				 int xStep = 5;
				 int xMax = 20;
				 for(Long l : resultMap.values()){
					 if(l>xMax){
						 xMax = (l.intValue()/xMax+1)*20;
						 xStep = xMax/4;
					 }
				 }
				 
				for(ResearchAnswer an: result.getData()){
					answerList.add(an);
//					System.out.println(an.getAnswer()+ " 票数为 "+ resultMap.get(an.getAnswerId()));
				}
				
			  ChartModel cm = new ChartModel(title.getQuestion(),  
		          "font-size: 14px; font-family: Verdana; text-align: center;");  
		      XAxis xa = new XAxis();  
		      xa.setRange(0, xMax, xStep);  
		      cm.setXAxis(xa);  
		      YAxis ya = new YAxis(); 
		      List<String> labels = new ArrayList<String>();
		      List<Long> vals = new ArrayList<Long>();
		      Long sum = new Long(0);
		      for(ResearchAnswer ra : answerList){
		    	  if(ra.getAnswer().length()>8){
		    		  ra.setAnswer(ra.getAnswer().substring(0, 8));
		    	  }
		    	  labels.add(ra.getAnswer());
		    	  vals.add(resultMap.get(ra.getAnswerId()));
		    	  sum += resultMap.get(ra.getAnswerId()); 
		      }
//		      System.out.println(labels+"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		      
//		      ya.addLabels("Ext", "Dojo", "jQuery", "YUI");
		      String[] colors = {"#ffff00","#0000ff","#00ff00","#ff0000"};
		      ya.addLabels(labels);
		      ya.setOffset(true);  
		      cm.setYAxis(ya);  
		      HorizontalBarChart bchart = new HorizontalBarChart();  
		      
//		      bchart.setTooltip("#val# 票" );  
		      for(int i = 0;i<vals.size();i++){
		    	  Bar bar= new HorizontalBarChart.Bar(vals.get(i), colors[i%4]);
		    	  String p = String.valueOf(new Float(vals.get(i)/sum.floatValue()*100));
		    	  p = p.substring(0, p.indexOf(".")+2);		    	  
		    	  bar.setTooltip(vals.get(i)+" 票  "  + p + " %" + " 共 "+sum +" 票");
//		    	 
		    	  bchart.addBars(bar);
		    	  
		      }

		      cm.addChartConfig(bchart);  
		      cm.setTooltipStyle(new ToolTip(MouseStyle.FOLLOW));  
		      chart.setChartModel(cm); 
			}
			
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("", "获取选项失败！", null);
				
			}
		});
		 
		 
	      
	    }  
	
	
	 //每题用一个图表表示
	 public Chart getChart(ResearchTitle title) {
	 	
			String url = "../../";
			url += "gxt/chart/open-flash-chart.swf";
			Chart chart = new Chart(url);
			chart.setBorders(true);
//			chart.setChartModel(new ChartModel("测试","font-size: 14px; font-family: Verdana; text-align: center;"));
			chart.setSize(440, 280);
			if(resultMap == null||title ==null){
				chart.setChartModel(getTestChartModel());
			}else{
				setTitleAndChartModel(title, chart);
			}
			
			return chart;
		}
	
	 public ChartModel getTestChartModel() {  
	      ChartModel cm = new ChartModel("随机测试数据",  
	          "font-size: 14px; font-family: Verdana; text-align: center;");  
	      XAxis xa = new XAxis();  
	      xa.setRange(0, 200, 50);  
	      cm.setXAxis(xa);  
	      YAxis ya = new YAxis();  
	      ya.addLabels("Ext", "Dojo", "jQuery", "YUI");  
	      ya.setOffset(true);  
	      cm.setYAxis(ya);  
	      HorizontalBarChart bchart = new HorizontalBarChart();  
	      bchart.setTooltip("#val# 票");  
	      bchart.addBars(new HorizontalBarChart.Bar(Random.nextInt(100) + 100, "#ffff00"));  
	      bchart.addBars(new HorizontalBarChart.Bar(Random.nextInt(100) + 100, "#0000ff"));  
	      bchart.addBars(new HorizontalBarChart.Bar(Random.nextInt(100) + 100, "#00ff00"));  
	      bchart.addBars(new HorizontalBarChart.Bar(Random.nextInt(100) + 100, "#ff0000"));  
	      cm.addChartConfig(bchart);  
	      cm.setTooltipStyle(new ToolTip(MouseStyle.FOLLOW));  
	      return cm;  
	    }  
	 
	 public void changeChartContainer(Research research , List<Long> studNumList){		
		 chartsContainer.removeAll();
		 if(research == null){
			 for(int i=0; i<2;i++){
				 chartsContainer.add(getChart(null));
			 }
			 return;
		 }
		 
		 PagingLoadConfig configt  = new BasePagingLoadConfig();
		 configt.set(ResearchManagerService.RESEARCHID, research.getResearchId());
		 configt.set(ResearchManagerService.STUDENT_NUMBERLIST, studNumList);
		 managerService.statisticsResearchResultPolls(configt, new AsyncCallback<Map<Long,Long>>() {
			
			@Override
			public void onSuccess(Map<Long, Long> result) {
				resultMap = result;
//				System.out.println("======================resultMap:"+ resultMap);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("","获取投票结果出错！", null);
				
			}
		});
		 
		 
		 
		 PagingLoadConfig config  = new BasePagingLoadConfig();
		 config.set(ResearchManagerService.RESEARCHID,research.getResearchId());
		 managerService.findResearchTitlesByPaging(config, new AsyncCallback<PagingLoadResult<ResearchTitle>>() {
			
			@Override
			public void onSuccess(PagingLoadResult<ResearchTitle> result) {
				
				 for(ResearchTitle title:result.getData()){
					 chartsContainer.add(getChart(title));
				 }				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("", "获取题目失败！", null);
				
			}
		});
		 
				 
//		 return container;
	 }
	 
	 
	
	
	
	/*
	 * 用于预览调研所处的题目 及 提交调研
	 */
	private ContentPanel createPreviewPanel(){
		
		
		Button delete = new Button("删除",new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {				
				if(tree.getSelectionModel().getSelectedItem()!=null){					
					MessageBox.confirm("警告", "是否要删除选中的节点？", new Listener<MessageBoxEvent>() {
						@Override
						public void handleEvent(MessageBoxEvent be) {
							Button but = be.getButtonClicked();
							if(but.getText().equalsIgnoreCase("Yes")||but.getText().equals("是")){
								store.remove(tree.getSelectionModel().getSelectedItem());
							}
						}
					});
				}
				
				
			}
		});
		
	    
		Button submit = new Button("提交", new SelectionListener<ButtonEvent>() {

			public void componentSelected(ButtonEvent ce) {
				
				if(startDate.getDatePicker().getValue() == null||startTime.getDateValue()==null||endDate.getDatePicker().getValue()==null||endTime.getDateValue()==null){
					MessageBox.alert("提示", "日期设置不正确", null);
					return;
				}
				
				if(topicText.getValue().equals("")){
					MessageBox.alert("提示", "请设置调研主题", null);
					return;
				}
				//new  一个调研
				Research research = new Research();
				research.setPubUserId(new Long(App.getUser().getUserID()));
				String sDate = DateTimeFormat.getFormat("yyyy-MM-dd").format(startDate.getDatePicker().getValue());				
				String sTime = DateTimeFormat.getFormat("HH:mm:ss").format(startTime.getDateValue());
				
				Timestamp ts = Timestamp.valueOf(sDate+" "+sTime);
				research.setStartTime(ts);
				String eDate = DateTimeFormat.getFormat("yyyy-MM-dd").format(endDate.getDatePicker().getValue());				
				String eTime = DateTimeFormat.getFormat("HH:mm:ss").format(endTime.getDateValue());
				Timestamp es =Timestamp.valueOf(eDate+" "+eTime);
				research.setEndTime(es);
				
				if(startDate.getDatePicker().getValue().after(endDate.getDatePicker().getValue()) ){
					MessageBox.alert("", "开始日期必须在结束时间之前！", null);
					return;
				}else if(startDate.getDatePicker().getValue().equals(endDate.getDatePicker().getValue())){
					if(startTime.getDateValue().after(endTime.getDateValue())){
						MessageBox.alert("", "开始时间必须在结束时间之前！", null);
						return;
					}
				}
				
				research.setTopic(topicText.getValue());

				Set<ResearchTitle> titleSet  = new LinkedHashSet<ResearchTitle>();
				Set<ResearchAnswer> answerSet = new LinkedHashSet<ResearchAnswer>();
				List<ModelData> models= store.getAllItems();
				for(ModelData eModel :models){
//					String  str = eModel.get("name");
					BaseTreeModel model = (BaseTreeModel) eModel;			
					//遍历一级目录下 题目 
						if(model.getParent()==null){
							ResearchTitle title = new ResearchTitle();
							//设置 调研和 题目的关联
							title.setResearch(research);
							title.setQuestion(model.get("name").toString());
							titleSet.add(title);
//							Set<ResearchAnswer> answerSet  = new LinkedHashSet<ResearchAnswer>();
							//有子项  是选择题 否则是简答题
							if(!model.isLeaf()){
								title.setType(POConstant.RESEARCHTITLETYPE.CHOICE);
								List<ModelData>  children = model.getChildren();
								for(ModelData child:children  ){
									BaseTreeModel anModel = (BaseTreeModel) child;
									ResearchAnswer answer = new ResearchAnswer();
									answer.setTitle(title);
									answer.setAnswer(anModel.get("name").toString());
									answerSet.add(answer);
								}
//								title.setAnswerSet(answerSet);
							}else{
								title.setType(POConstant.RESEARCHTITLETYPE.FILL);
							}
						}
					
					
				}
				
				
				PagingLoadConfig config = new BasePagingLoadConfig();
				config.set(ResearchManagerService.RESEARCH, research);
				config.set(ResearchManagerService.RESEARCH_TITLE_SET, titleSet);
				config.set(ResearchManagerService.RESEARCH_ANSWER_SET,answerSet);
				managerService.saveResearchByPaging(config, new AsyncCallback<Void>() {
					
					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub
						MessageBox.alert("success", "提交成功", null);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						MessageBox.alert("fail", "fail", null);
					}
				});
				
				
			}
		});
		
		
		store= new TreeStore<ModelData>();
	    tree = new TreePanel<ModelData>(store);  

	    tree.setDisplayProperty("name");
	    tree.setAutoSelect(true);

	    ContentPanel treePanel  = new ContentPanel();
	    treePanel.setScrollMode(Scroll.AUTO);
	    treePanel.setLayout(new FitLayout());
	    treePanel.add(tree); 
	    treePanel.addButton(delete);
	    treePanel.addButton(submit);
	    treePanel.setHeading("预览");
	    return treePanel;
	}
	
	/*
	 * 创建调研所用的表单
	 */
	public FormPanel createFormPanle(){
		//表单开始
	    FormData formData = new FormData("100%");  
	    final FormPanel formPanel = new FormPanel();
	    formPanel.setLayoutOnChange(true);
	    formPanel.setFrame(true);  
	    formPanel.setHeading("编辑");  
	    formPanel.setSize(600, -1);  
	  
	    LayoutContainer main = new LayoutContainer();  
	    main.setLayout(new ColumnLayout());  
	  
	    LayoutContainer left = new LayoutContainer();  
	    left.setStyleAttribute("paddingRight", "10px");  
	    FormLayout layout = new FormLayout();  
//	    layout.setLabelAlign(LabelAlign.TOP);  	    
	    left.setLayout(layout);  
	  
	    startDate = new DateField();  
	    startDate.setFieldLabel("开始日期");  
	    left.add(startDate, formData);  
	    
	    
	    endDate = new DateField();  
	    endDate.setFieldLabel("结束日期");  
	    left.add(endDate, formData);  
	    
	    LayoutContainer right = new LayoutContainer();  
	    right.setStyleAttribute("paddingLeft", "10px");  
	    layout = new FormLayout();    
	    right.setLayout(layout);  
	  
	    
	    startTime =new TimeField();
	    startTime.setFieldLabel("开始时间");
	    right.add(startTime, formData);
	    
	    
	    endTime =new TimeField();
	    endTime.setFieldLabel("结束时间");
	    endTime.addSelectionChangedListener(new SelectionChangedListener<Time>() {
			
			@Override
			public void selectionChanged(SelectionChangedEvent<Time> se) {
				editor.setEnabled(true);
				editor.setValue("");
				
			}
		});
	    right.add(endTime, formData);
	    
	    
	    editor = new HtmlEditor();  
	    editor.setFieldLabel("文本编辑器");  
	    editor.setHeight(200);
	    editor.setValue("请先填写好日期,在此处编辑文字后请点击\"添加为调研住题\"作为主题，或点击\"作为题目添加\"为本次投票添加题目，或点击\"作为备选答案添加\"添加为相关题目的答案...");
	    editor.setEnabled(false);
	    
	    topicText =new TextField<String>();
	    topicText.setFieldLabel("调研主题");	    
	    topicText.setEnabled(false);
	   

	    main.add(left, new ColumnData(.5));  
	    main.add(right, new ColumnData(.5));  
	    
	    
	    formPanel.add(main, new FormData("100%"));  
	    formPanel.add(topicText,new FormData("100%"));
	    formPanel.add(editor, new FormData("100%"));  
	    Button topicButton =new Button("添加为调研主题",new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				if(editor.getValue()==null||editor.getValue().trim().equals("")||editor.getValue().trim().equals("<br>")){
					MessageBox.alert("警告", "不能添加空主题！", null);
					return;
				}
				topicText.setValue(editor.getValue());
				editor.setValue("");
			}
		});
	    Button titleButton =new Button("作为题目添加",new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {	
				if(editor.getValue()==null||editor.getValue().trim().equals("")||editor.getValue().trim().equals("<br>")){
					MessageBox.alert("警告", "不能添加空题目！", null);
					return;
				}
				BaseTreeModel model =new BaseTreeModel();
				model.set("name", editor.getValue());				
				store.add(model, true);
				tree.getSelectionModel().select(model,false);
				editor.setValue("");
			}
		});
	    Button answerButton =new Button("作为备选答案添加",new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				TreePanelSelectionModel<ModelData> models = tree.getSelectionModel();
				if(editor.getValue()==null||editor.getValue().trim().equals("")||editor.getValue().trim().equals("<br>")){
					MessageBox.alert("警告", "不能添加空答案！", null);
					return;
				}
				if(models!=null){
					BaseTreeModel model = (BaseTreeModel) models.getSelectedItem();
					if(model!=null&&model.getParent()==null){
						BaseTreeModel m = new BaseTreeModel(model);
						m.set("name", editor.getValue());
						store.add(model,m,false);
						tree.getSelectionModel().select(m,false);
						editor.setValue("");
					}else if(model!=null&&model.getParent().getParent()==null){
						BaseTreeModel m = new BaseTreeModel(model.getParent());
						m.set("name", editor.getValue());
						store.add(model.getParent(),m,false);
						tree.getSelectionModel().select(m,false);
						editor.setValue("");
					}
					
				}

			}
		});
	    Button get = new Button("查看选中节点", new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				TreePanelSelectionModel<ModelData> m = tree.getSelectionModel(); 
				if(m!=null){
					BaseTreeModel model = (BaseTreeModel) m.getSelectedItem();
					if(model!=null){
						MessageBox.alert("",model.get("name").toString(),null);
						if(model.getParent()!=null)
							MessageBox.alert("parent",model.getParent().get("name").toString(),null);
						
					}				
				}
			}
		});
	    formPanel.addButton(topicButton);
	    formPanel.addButton(titleButton);  
	    formPanel.addButton(answerButton);
	    formPanel.addButton(get);
	    formPanel.show();
	    formPanel.setScrollMode(Scroll.AUTO);
	    return formPanel;
	}
	
}
